<?php
namespace App\Repositories\BLL;

use App\Repositories\BLL\Repository;
use App\Models\Wechat\MsgRule;
use Illuminate\Support\Facades\DB;

class MsgRuleBLL extends Repository
{

        
    public function model()
    {
        return MsgRule::class;
    }
    
    public function ajaxIndex($currentRouteName)
    {
        // datatables请求次数
        $draw = request('draw', 1);
    	// 开始条数
        $start = request('start', config('admin.global.list.start'));
        // 每页显示数目
        $length = request('length', config('admin.global.list.length'));
        // 排序
        $order['name'] = request('columns.' .request('order.0.column', 0) . '.name');
        $order['dir'] = request('order.0.dir', 'asc');

        $search['value'] = request('search.value', '');

        $search['regex'] = request('search.regex', false);

        $MsgRule = $this->model;

        // 搜索框中的值
        if ($search['value']) {
            if ($search['regex'] == 'true') {
                $MsgRule = $MsgRule->where('msg', 'like', "%{$search['value']}%");
            } else {
                $MsgRule = $MsgRule->where('msg', $search['value']);
            }
        }

        $count = $MsgRule->count();

        $MsgRule = $MsgRule->orderBy($order['name'], $order['dir']);
        $MsgRules = $MsgRule->offset($start)->limit($length)->get();
            
        $pointPost = strrpos($currentRouteName, '.');
        $parentUrl = substr($currentRouteName, 0, $pointPost);
        if ($MsgRules) {
            foreach ($MsgRules as &$v) {
                $v->actionButton = $v->getListActionButton($currentRouteName);
                
            }
        }

		//datatables固定返回格式
		return [
		'draw' => $draw,
		'recordsTotal' => $count,
		'recordsFiltered' => $count,
		'data' => $MsgRules,
		];
    }

    public function createEntity($attributes,$successMsg = "创建成功", $errorMsg = "创建失败")
    {
        $result = $this->create($attributes);
        if ($result) {
            flash($successMsg);
        } else {
            flash($errorMsg, 'error');
        }
        return $result;
    }
    
    public function editView($id)
    {
        $MsgRule = $this->find($id);
        if ($MsgRule) {
            return $MsgRule;
        }
        abort(404);
    }

    public function updateEntity($attributes, $id, $successMsg = "修改成功", $errorMsg = "修改失败")
    {
        $result = $this->update($attributes, $id);
        if ($result) {
            flash($successMsg);
        } else {
            flash($errorMsg, 'error');
        }
        return $result;
    }

    public function destroyEntity($id, $successMsg = "删除成功", $errorMsg = "删除失败")
    {
        $result = $this->delete($id);
        if ($result) {
            flash($successMsg);
        } else {
            flash($errorMsg, 'error');
        }
        return $result;
    }
    
    /**
     * 获取所有角色
     */
    public function getAllEntity()
    {
        $MsgRules = $this->all();
        return $MsgRules;
    }
}
